package cn.ffcs.uec.outStaffEntryApply.component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zul.Div;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.kernel.annotation.Transactional;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.organization.manager.UecOrgDeptManager;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgDept;
import cn.ffcs.uec.organization.model.UecOrgOrgs;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaff.vo.UecOutStaffInfoVo;
import cn.ffcs.uec.outStaffEntryApply.component.bean.OutStaffEntryApplyListboxExtBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecPsnjobManager;
import cn.ffcs.uec.staff.manager.UecTrialManager;
import cn.ffcs.uec.staff.model.UecDocEdu;
import cn.ffcs.uec.staff.model.UecEnc;
import cn.ffcs.uec.staff.model.UecFamily;
import cn.ffcs.uec.staff.model.UecNationduty;
import cn.ffcs.uec.staff.model.UecPartyLog;
import cn.ffcs.uec.staff.model.UecPsndocWadoc;
import cn.ffcs.uec.staff.model.UecPsnjob;
import cn.ffcs.uec.staff.model.UecPunish;
import cn.ffcs.uec.staff.model.UecTitle;
import cn.ffcs.uec.staff.model.UecTrial;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;
import lombok.Getter;
import lombok.Setter;

@Controller
@Scope("prototype")
public class OutStaffEntryApplyListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -6692445582775895515L;

	private static final String OUT_STAFF_ENTRY_APPLY_LISTBOX_EXT_ZUL = "/pages_nmg/outStaffEntryApply/comp/outStaffEntryApply_listbox_ext.zul";

	public static Boolean ORG_CHANGE_FLAG = false;
	/**
	 * 页面对应的bean
	 */
	private OutStaffEntryApplyListboxExtBean bean = new OutStaffEntryApplyListboxExtBean();

	/**
	 * 外包人员基本信息对象
	 */
	private UecOutStaffInfo uecOutStaffInfo;
	private UecOutStaffInfo qryUecOutStaffInfo;

	/**
	 * 外包人员虚拟对象
	 */
	private UecOutStaffInfoVo uecOutStaffInfoVo;
	/**
	 * 人员试用情况
	 */
	private UecTrial uecTrial;
	private UecTrial qryUecTrial;

	/**
	 * 任职信息表
	 */
	private UecPsnjob uecPsnjob;
	/**
	 * 薪资变动情况
	 */
	private UecPsndocWadoc uecPsndocWadoc;
	/**
	 * 教育经历 Tab 增加的记录
	 */
	private List<UecDocEdu> eduList;
	/**
	 * 人员家庭情况 Tab 增加的记录
	 */
	private List<UecFamily> families;
	/**
	 * 专业技术职务 Tab 增加的记录
	 */
	private List<UecTitle> titleList;
	/**
	 * 职业资格 Tab 增加的记录
	 */
	private List<UecNationduty> nationdutyList;
	/**
	 * 奖励 Tab 增加的记录
	 */
	private List<UecEnc> encList;
	/**
	 * 惩罚 Tab 增加的记录
	 */
	private List<UecPunish> punishList;

	private List<UecPartyLog> partyLogList;

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");
	private UecOrgDeptManager uecOrgDeptManager = (UecOrgDeptManager) ApplicationContextUtil
			.getBean("uecOrgDeptManager");
	private UecPsnjobManager uecPsnjobManager = (UecPsnjobManager) ApplicationContextUtil.getBean("uecPsnjobManager");

	private UecTrialManager uecTrialManager = (UecTrialManager) ApplicationContextUtil.getBean("uecTrialManager");
    private String newOrg="";
	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public OutStaffEntryApplyListboxExt() {
		Executions.createComponents(OUT_STAFF_ENTRY_APPLY_LISTBOX_EXT_ZUL, this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');
	}

	/**
	 * 界面初始化
	 */
	public void onCreate() {
		bandListbox();
	}

	/**
	 * 监听UecOutDocEduListboxExt 传出的事件
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onPostEduListOfOutStaffEntryResponse(ForwardEvent event) {
		if (null != event.getOrigin().getData()) {
			eduList = (List<UecDocEdu>) event.getOrigin().getData();
		}
	}

	/**
	 * 监听UecOutStaffFamilyListboxExt 传出的事件
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onPostFamilyListOfOutStaffEntryResponse(ForwardEvent event) {
		if (null != event.getOrigin().getData()) {
			families = (List<UecFamily>) event.getOrigin().getData();
		}
	}

	/**
	 * 监听UecOutStaffTitleListboxExt 传出的事件
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onPostTitleListOfOutStaffEntryResponse(ForwardEvent event) {
		if (null != event.getOrigin().getData()) {
			titleList = (List<UecTitle>) event.getOrigin().getData();
		}
	}

	/**
	 * 监听UecOutStaffNationdutyListboxExt 传出的事件
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onPostNationdutyListOfOutStaffEntryResponse(ForwardEvent event) {
		if (null != event.getOrigin().getData()) {
			nationdutyList = (List<UecNationduty>) event.getOrigin().getData();
		}
	}

	/**
	 * 监听UecOutStaffEncListboxExt 传出的事件
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onPostEncListOfOutStaffEntryResponse(ForwardEvent event) {
		if (null != event.getOrigin().getData()) {
			encList = (List<UecEnc>) event.getOrigin().getData();
		}
	}

	/**
	 * 监听UecOutStaffPunishListboxExt 传出的事件
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onPostPunishListOfOutStaffEntryResponse(ForwardEvent event) {
		if (null != event.getOrigin().getData()) {
			punishList = (List<UecPunish>) event.getOrigin().getData();
		}
	}

	/**
	 * 监听UecOutStaffPartyLogListboxExt 传出的事件
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onPostPartyLogListOfOutStaffEntryResponse(ForwardEvent event) {
		if (null != event.getOrigin().getData()) {
			partyLogList = (List<UecPartyLog>) event.getOrigin().getData();
		}
	}

	/**
	 * 查询按钮 根据条件查询
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */
	public void onQuery() throws SuspendNotAllowedException, Exception {
		clearVariable();
		uecOutStaffInfoVo = new UecOutStaffInfoVo();
		/**
		 * 组织树Ext UecOrganizationTreeBandboxExt 组织树上有组织和部门 通过组织树获取组织或部门
		 */
		if (!StrUtil.isNullOrEmpty(bean.getOutStaffPkHrorg().getValue())) {
			// 组织类型：公司 or 部门
			String orgType = (String) bean.getOutStaffPkHrorg().getOrganization().getOrgType();
			String pkorg = (String) bean.getOutStaffPkHrorg().getOrganization().getOrg();
			if ("ORG".equals(orgType)) {
				// 组织主键
				String orgName = (String) bean.getOutStaffPkHrorg().getOrganization().getOrgName();
				// 公司
			//	uecOutStaffInfoVo.setPkOrg(pkorg);
				 if("中国电信股份有限公司内蒙古分公司".equals(orgName)) {
			       		uecOutStaffInfoVo
			       		.setOrgName(null);
			       	}else if(orgName.endsWith("*")){
			       		uecOutStaffInfoVo
			       		.setOrgName(orgName);
			       	}else {
			       		uecOutStaffInfoVo.setPkOrg(pkorg);
			       	}	
				
			} else {
				// 部门
				UecOrgDept uecOrgDept = new UecOrgDept();
				UecOrgOrgs uecOrgOrgs = new UecOrgOrgs();
				uecOrgDept.setPkDept(pkorg);
				uecOrgDept = uecOrgDeptManager.findUecOrgDeptByOrgDept(uecOrgDept);
				// 部门所属公司
				if(uecOrgDept !=null) {
					uecOrgOrgs= new UecOrgOrgs();
					uecOrgOrgs.setPkOrg(uecOrgDept.getPkOrg());
					uecOrgOrgs = uecOrgOrgsManager.findUecOrgOrgsByUecOrgOrgs(uecOrgOrgs);
					String orgName=uecOrgOrgs.getName();
					uecOutStaffInfoVo.setPkDept(uecOrgDept.getPkDept());
					uecOutStaffInfoVo.setPkOrg(uecOrgDept.getPkOrg());
					uecOutStaffInfoVo.setOrgName(orgName);

				//uecOutStaffInfoVo.setPkDept(pkorg);
			}
		}
		}
		uecOutStaffInfoVo.setStaffCode(bean.getOutStaffCode().getValue());
		uecOutStaffInfoVo.setStaffName(bean.getOutStaffName().getValue());
		uecOutStaffInfoVo.setIdNum(bean.getOutStaffIdNum().getValue());
		// 查询员工
		outStaffList();

	
}
	/**
	 * 员工列表
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */

	public void outStaffList() throws SuspendNotAllowedException, Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", "outStaffList");
		map.put("uecOutStaffInfoVo", uecOutStaffInfoVo);
		Window window = (Window) Executions.createComponents(UecOutStaffConstants.UEC_OUT_STAFF_LIST_ZUL, this, map);
		window.doModal();
		window.addEventListener("onOK", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (event.getData() != null) {
					qryUecOutStaffInfo = (UecOutStaffInfo) event.getData();
					uecOutStaffInfo = qryUecOutStaffInfo;
					postEventOfOutStaff();
					/**
					 * 入职申请一个人只能申请一次 根据staffId和nmStaffType在人员试用情况表中查 不存在记录才允许进行入职申请
					 */
					qryUecTrial = UecTrial.newInstance();
					qryUecTrial.setStaffId(qryUecOutStaffInfo.getOutStaffId());
					qryUecTrial.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
					qryUecTrial = uecTrialManager.findUecTrial(qryUecTrial);
					String procDefId = ApprovalConstants.OUT_STAFF_ENTRY_PROC_DEF_ID;
					boolean isOnApproval = ApprovalUtil.isOnApproval(procDefId, uecOutStaffInfo.getOutStaffId());
					if (isOnApproval) {
						ZkUtil.showError("在审状态不允许发起！", "错误提示");
						return;
					}
					/**
					 * 如果试用信息不为空，标识此人已经入职
					 */
					// 判断本组织 人员试用情况是否为null
					// 组织
					UecPsnjob	uecPsnjob=new UecPsnjob();
					uecPsnjob.setStaffId(qryUecOutStaffInfo.getOutStaffId());
					uecPsnjob.setNmStaffType("2");
					UecPsnjob findNewUecPsnjob = uecPsnjobManager.findNewUecPsnjob(uecPsnjob);
					if (StrUtil.isNullOrEmpty(qryUecTrial) && !findNewUecPsnjob.getPkOrg().equals(!StrUtil.isNullOrEmpty(qryUecTrial.getPkOrg())?qryUecTrial.getPkOrg():"")) {
						PubUtil.fillBeanFromPo(qryUecOutStaffInfo, bean);
						// 重新绑定下日期
						// 参加工作日期
						bean.getJoinWorkDate()
								.setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getJoinWorkDate()));
						// 进入电信系统日期
						bean.getGlbdef3().setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getGlbdef3()));
						// 身故日期
						bean.getDieDate().setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getDieDate()));
						// 进入本单位日期
						bean.getEnterUnitTime()
								.setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getEnterUnitTime()));
						String uecOrgOrgsNameByPkOrg = uecOrgOrgsManager.getUecOrgOrgsNameByPkOrg(findNewUecPsnjob.getPkOrg());
						newOrg=findNewUecPsnjob.getPkOrg();
						if (!StrUtil.isNullOrEmpty(uecOrgOrgsNameByPkOrg)) {
							//String orgName = uecOrgOrgsManager
									//.getUecOrgOrgsNameByPkOrg(qryUecOutStaffInfo.getPkHrorg());
							bean.getPkHrorgName().setValue(uecOrgOrgsNameByPkOrg);
						}
					} else {
						ZkUtil.showInformation("此人已经入职！", "温馨提示");
					}
				}
			}
		});
	}

	private void postEventOfOutStaff() {
		// 把员工对象抛出到各Ext
		Events.postEvent(UecOutStaffConstants.ON_UEC_OUT_STAFF_INFO_QUERY, this, uecOutStaffInfo);
	}

	/**
	 * 入职申请流程发起按钮
	 * 
	 * @throws Exception
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void onLaunchEntryApply() throws Exception {
		if (null == uecOutStaffInfo || null == uecOutStaffInfo.getOutStaffId()) {
			ZkUtil.showError("未获取人员！", "错误提示");
			return;
		}
		// 入职前字段校验
		String msg = this.checkUacStaffData();
		if (null != msg) {
			Messagebox.show(msg);
			return;
		}
		// 获取登录人
		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前登录用户不存在!", "错误提示");
			return;
		}
		String currentName = PlatformUtil.getCurrentUser().getScreenName();

		// 获取bean内的所有数据到对象
		PubUtil.fillPoFromBean(bean, uecOutStaffInfo);
		// 获取日期并格式化
		// 参加工作日期
		uecOutStaffInfo.setJoinWorkDate(DateUtil.dateToStr(bean.getJoinWorkDate().getValue()));
		// 进入电信系统日期
		uecOutStaffInfo.setGlbdef3(DateUtil.dateToStr(bean.getGlbdef3().getValue()));
		// 身故日期
		uecOutStaffInfo.setDieDate(DateUtil.dateToStr(bean.getDieDate().getValue()));
		// 进入本单位日期
		uecOutStaffInfo.setEnterUnitTime(DateUtil.dateToStr(bean.getEnterUnitTime().getValue()));
		
		// 工龄
		Integer workYears = getWorkingYears(qryUecOutStaffInfo.getJoinWorkDate());
		uecOutStaffInfo.setDef3(workYears.toString());
		// 本企业工龄：当前日期 – 进入本单位日期
		Integer theWorkYears = getWorkingYears(qryUecOutStaffInfo.getEnterUnitTime());
		uecOutStaffInfo.setDef4(theWorkYears.toString());
		// 预计退休日期：男=出生日期+60年;女=出生日期+50年
		Date retiredDate = getRetiredDate(qryUecOutStaffInfo.getSex(), qryUecOutStaffInfo.getIdNum());
		uecOutStaffInfo.setGlbdef15(new SimpleDateFormat("yyyy-MM-dd").format(retiredDate));
		// 创建人：数据是集团NC 下发带有该数据的不动，其它模块取登录系统人员的账号作为创建人
		// 获取修改人
		uecOutStaffInfo.setModifier(currentName);
		// 修改时间：取当前时间
		uecOutStaffInfo.setModifiedTime(DateUtil.getCurrenDate());
		/**
		 * 获取人员试用情况数据
		 */
		uecTrial = new UecTrial();
		PubUtil.fillPoFromBean(bean, uecTrial);
		// 获取staffId
		uecTrial.setStaffId(uecOutStaffInfo.getOutStaffId());
		// 设置状态，非常重要！
		uecTrial.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		// 获取pk_psndoc
		uecTrial.setPkPsndoc(uecOutStaffInfo.getPkPsnMsg());
		// 获取试用类型
		Object value = bean.getTrialType().getSelectedItem().getValue();
		Long trialType = Long.valueOf(String.valueOf(value));
		uecTrial.setTrialType(trialType);
		// 同步组织
		uecTrial.setPkOrg(newOrg);
		// 获取试用开始日期
		uecTrial.setBegindate(DateUtil.dateToStr(bean.getBegindate().getValue()));
		// 获取试用结束日期
		uecTrial.setEnddate(DateUtil.dateToStr(bean.getEnddate().getValue()));

		// 创建人：数据是集团NC 下发带有该数据的不动，其它模块取登录系统人员的账号作为创建人
		// 获取登录用户名，创建人
		uecTrial.setCreator(currentName);
		// 创建时间：取当前时间
		uecTrial.setCreationtime(String.valueOf(DateUtil.getCurrenDate()));

		// 发起流程
		if (ApprovalUtil.getActivityFlag()) {
			String procDefId = ApprovalConstants.OUT_STAFF_ENTRY_PROC_DEF_ID;
			// 判断该人员是否在审状态，如果是在审状态不允许再次发起此流程
			boolean isOnApproval = ApprovalUtil.isOnApproval(procDefId, uecOutStaffInfo.getOutStaffId());
			if (isOnApproval) {
				ZkUtil.showError("在审状态不允许发起！", "错误提示");
				return;
			}
			if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
				ZkUtil.showError("当前登录用户不存在!", "错误提示");
				return;
			}

			String appendPrimaryId = "";
			String eduIds = "";
			if (null == eduList || eduList.size() == 0) {
				ZkUtil.showError("请添加教育经历信息!", "错误提示");
				return;
			}
			if (null == titleList || titleList.size() == 0) {
				ZkUtil.showError("请添加专业技术职务信息!", "错误提示");
				return;
			}
			if (null == nationdutyList || nationdutyList.size() == 0) {
				ZkUtil.showError("请添加职业资格管理信息!", "错误提示");
				return;
			}
			if (null == partyLogList || partyLogList.size() == 0) {
				ZkUtil.showError("请添加政治面貌信息!", "错误提示");
				return;
			}

			if (!StrUtil.isNullOrEmpty(eduList) && eduList.size() > 0) {
				for (UecDocEdu uecDocEdu : eduList) {
					uecDocEdu.addStatusCdIS3();
					eduIds += uecDocEdu.getEduId() + "-";
				}
				eduIds = eduIds.substring(0, eduIds.length() - 1);
				appendPrimaryId += ",uec_doc_edu:" + eduIds;
			}
			String familyIds = "";
			if (!StrUtil.isNullOrEmpty(families) && families.size() > 0) {
				for (UecFamily uecFamily : families) {
					uecFamily.addStatusCdIS3();
					familyIds += uecFamily.getFamilyId() + "-";
				}
				familyIds = familyIds.substring(0, familyIds.length() - 1);
				appendPrimaryId += ",uec_family:" + familyIds;
			}
			String titleIds = "";
			if (!StrUtil.isNullOrEmpty(titleList) && titleList.size() > 0) {
				for (UecTitle uecTitle : titleList) {
					uecTitle.addStatusCdIS3();
					titleIds += uecTitle.getTitleId() + "-";
				}
				titleIds = titleIds.substring(0, titleIds.length() - 1);
				appendPrimaryId += ",uec_title:" + titleIds;
			}
			String nationdutyIds = "";
			if (!StrUtil.isNullOrEmpty(nationdutyList) && nationdutyList.size() > 0) {
				for (UecNationduty nationduty : nationdutyList) {
					nationduty.addStatusCdIS3();
					nationdutyIds += nationduty.getNationdutyId() + "-";
				}
				nationdutyIds = nationdutyIds.substring(0, nationdutyIds.length() - 1);
				appendPrimaryId += ",uec_nationduty:" + nationdutyIds;
			}
			String encIds = "";
			if (!StrUtil.isNullOrEmpty(encList) && encList.size() > 0) {
				for (UecEnc uecEnc : encList) {
					uecEnc.addStatusCdIS3();
					encIds += uecEnc.getEncId() + "-";
				}
				encIds = encIds.substring(0, encIds.length() - 1);
				appendPrimaryId += ",uec_enc:" + encIds;
			}
			String punishIds = "";
			if (!StrUtil.isNullOrEmpty(punishList) && punishList.size() > 0) {
				for (UecPunish uecPunish : punishList) {
					uecPunish.addStatusCdIS3();
					punishIds += uecPunish.getPunishId() + "-";
				}
				punishIds = punishIds.substring(0, punishIds.length() - 1);
				appendPrimaryId += ",uec_punish:" + punishIds;
			}
			String partyLogIds = "";
			if (!StrUtil.isNullOrEmpty(partyLogList) && partyLogList.size() > 0) {
				for (UecPartyLog uecPartyLog : partyLogList) {
					uecPartyLog.addStatusCdIS3();
					partyLogIds += uecPartyLog.getPartylogId() + "-";
				}
				partyLogIds = partyLogIds.substring(0, partyLogIds.length() - 1);
				appendPrimaryId += ",uec_partylog:" + partyLogIds;
			}

			/**
			 * 数据入库 uec_out_staff_info 修改一条记录，uec_trial 添加一条记录
			 */
			Long outStaffIdHis = uecOutStaffInfo.getOutStaffId();

			uecOutStaffInfo.addStatusCdIS3();
			Long outStaffId = uecOutStaffInfo.getOutStaffId();

			uecTrial.addStatusCdIS3();
			Long uecTrialId = uecTrial.getTrialId();

			String formTheme = "盟市外包人员入职流程";

			String startFlowJson = "{" + "formTheme: '" + formTheme + "'," + " formContent: '入职人员:"
					+ uecOutStaffInfo.getPsnName() + "'," + " procDefId: '"
					+ ApprovalConstants.OUT_STAFF_ENTRY_PROC_DEF_ID + "'," + " urgent: '1'," + " atiActCategoryId: '"
					+ ApprovalConstants.ENTRY_CATEGORY_ID + "'," + " procDefKey: '" + ApprovalUtil.OUT_STAFF_ENTRY
					+ "'," + " formSender: '" + currentName + "'," + " primaryId: '{" + "uec_out_staff_info_his:"
					+ outStaffIdHis + ",uec_out_staff_info:" + outStaffId + ",uec_trial:" + uecTrialId + appendPrimaryId
					+ "'}";

			String procInstId = null;
			try {
				procInstId = ApprovalUtil.startApproval(startFlowJson);
			} catch (Exception e) {
				// 流程发起失败 数据改为失效
				uecOutStaffInfo.removeOnly();
				uecTrial.removeOnly();
				setTabsDataInActive();
				onReset();
				e.printStackTrace();
				ZkUtil.showError("流程发起失败！", "错误提示");
			}

			if (StrUtil.isNullOrEmpty(procInstId)) {
				uecOutStaffInfo.removeOnly();
				uecTrial.removeOnly();
				setTabsDataInActive();
				onReset();
				ZkUtil.showError("流程发起失败！", "错误提示");
				return;
			}
			// 第一审批人如果是发起人直接到人力审批环节
			ApprovalUtil.isCurrentAssignNames(procInstId);

			ApprovalUtil.showNextAssignee(procInstId, formTheme);

			onReset();
		} else {
			// 历史人员数据更新
			uecOutStaffInfo.updateOnly();

			if (null != uecPsnjob) {
				uecPsnjob.setStaffId(uecOutStaffInfo.getOutStaffId());
				uecPsnjob.updateOnly();
			}
			if (null != uecPsndocWadoc) {
				uecPsndocWadoc.setStaffId(uecOutStaffInfo.getOutStaffId());
				uecPsndocWadoc.updateOnly();
			}

			uecTrial.setStaffId(uecOutStaffInfo.getOutStaffId());
			uecTrial.addOnly();

			setTabsDataActive();

			ZkUtil.showInformation("数据保存成功", "温馨提示");
			onReset();
		}

	}

	/**
	 * 流程发起失败，Tabs添加的数据失效
	 */
	private void setTabsDataInActive() {
		if (!StrUtil.isNullOrEmpty(eduList) && eduList.size() > 0) {
			for (UecDocEdu uecDocEdu : eduList) {
				uecDocEdu.removeOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(families) && families.size() > 0) {
			for (UecFamily uecFamily : families) {
				uecFamily.removeOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(titleList) && titleList.size() > 0) {
			for (UecTitle uecTitle : titleList) {
				uecTitle.removeOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(nationdutyList) && nationdutyList.size() > 0) {
			for (UecNationduty nationduty : nationdutyList) {
				nationduty.removeOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(encList) && encList.size() > 0) {
			for (UecEnc uecEnc : encList) {
				uecEnc.removeOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(punishList) && punishList.size() > 0) {
			for (UecPunish uecPunish : punishList) {
				uecPunish.removeOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(partyLogList) && partyLogList.size() > 0) {
			for (UecPartyLog uecPartyLog : partyLogList) {
				uecPartyLog.removeOnly();
			}
		}
	}

	/**
	 * Tabs数据生效
	 */
	private void setTabsDataActive() {
		if (!StrUtil.isNullOrEmpty(eduList) && eduList.size() > 0) {
			for (UecDocEdu uecDocEdu : eduList) {
				uecDocEdu.addOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(families) && families.size() > 0) {
			for (UecFamily uecFamily : families) {
				uecFamily.addOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(titleList) && titleList.size() > 0) {
			for (UecTitle uecTitle : titleList) {
				uecTitle.addOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(nationdutyList) && nationdutyList.size() > 0) {
			for (UecNationduty nationduty : nationdutyList) {
				nationduty.addOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(encList) && encList.size() > 0) {
			for (UecEnc uecEnc : encList) {
				uecEnc.addOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(punishList) && punishList.size() > 0) {
			for (UecPunish uecPunish : punishList) {
				uecPunish.addOnly();
			}
		}
		if (!StrUtil.isNullOrEmpty(partyLogList) && partyLogList.size() > 0) {
			for (UecPartyLog uecPartyLog : partyLogList) {
				uecPartyLog.addOnly();
			}
		}

	}

	/**
	 * 重置按钮
	 */
	public void onReset() {
		clearVariable();
		PubUtil.clearComponent(this);
		Events.postEvent(UecOutStaffConstants.ON_CLEAN_TAB_UEC_OUT_STAFF_INFO_QUERY, this, null);
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecTrial = null;
		uecOutStaffInfo = null;
		uecOutStaffInfoVo = null;
	}

	/**
	 * 绑定Listbox
	 */
	public void bandListbox() {
		// 健康状况
		ListboxUtils.rendererForEdit(bean.getHealth(), NodeVoUtil.getDictionaries(UecConstants.HELATH));
		// 绑定民族nationality
		ListboxUtils.rendererForEdit(bean.getNationality(), NodeVoUtil.getDictionaries(UecConstants.NATION));
		// 婚姻状况marital
		ListboxUtils.rendererForEdit(bean.getMarital(), NodeVoUtil.getDictionaries(UecConstants.MARRIAGE));
		// 政治面貌
		ListboxUtils.rendererForEdit(bean.getPolity(), NodeVoUtil.getDictionaries(UecConstants.POLITICAL_OUTLOOK));
		// 户口性质characterrpr
		ListboxUtils.rendererForEdit(bean.getCharacterrpr(),
				NodeVoUtil.getDictionaries(UecConstants.NATURE_REGISTRATION));
		// 进入电信系统来源--glbdef2
		ListboxUtils.rendererForEdit(bean.getGlbdef2(),
				NodeVoUtil.getDictionaries(UecConstants.ASSCESS_SOURCE_TELESTSTEM));
		// 绑定查询选项下拉框
		/**
		 * 人员属性--property 0:合同制用工 1：派遣制用工 2：外包自有 3：外包其他
		 */
		List<NodeVo> nodeVoPropertyList = new ArrayList<NodeVo>();
		String[][] property = { { "2", "外包自有" }, { "3", "外包其他" } };
		for (int i = 0; i < property.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(property[i][j]);
				nodeVo.setName(property[i][j + 1]);
			}
			nodeVoPropertyList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getProperty(), nodeVoPropertyList);

		// 绑定启用状态
		List<NodeVo> nodeVoEnableStateList = new ArrayList<NodeVo>();
		String[][] enableState = { { "1", "未启用" }, { "2", "已启用" }, { "3", "已停用" } };
		for (int i = 0; i < enableState.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(enableState[i][j]);
				nodeVo.setName(enableState[i][j + 1]);
			}
			nodeVoEnableStateList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getEnableState(), nodeVoEnableStateList);

		// 是否是历史成员
		List<NodeVo> nodeVoIshiskeypsnList = new ArrayList<NodeVo>();
		String[][] ishiskeypsn = { { "Y", "是" }, { "N", "否" } };
		for (int i = 0; i < ishiskeypsn.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(ishiskeypsn[i][j]);
				nodeVo.setName(ishiskeypsn[i][j + 1]);
			}
			nodeVoIshiskeypsnList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getIshiskeypsn(), nodeVoIshiskeypsnList);
		// 是否是门店营业员
		ListboxUtils.rendererForEdit(bean.getIsshopassist(), nodeVoIshiskeypsnList);
		// 是否承包经营个人
		ListboxUtils.rendererForEdit(bean.getGlbdef14(), nodeVoIshiskeypsnList);

		/**
		 * 人员试用情况
		 */
		// 试用类型trialType
		List<NodeVo> nodeVoTrialTypeList = new ArrayList<NodeVo>();
		String[][] trialType = { { "1", "转岗试用" }, { "2", "入职试用" } };
		for (int i = 0; i < trialType.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(trialType[i][j]);
				nodeVo.setName(trialType[i][j + 1]);
			}
			nodeVoTrialTypeList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getTrialType(), nodeVoTrialTypeList);
	}

	/**
	 * 计算工龄（年）
	 * 
	 * @param joinWorkDate
	 * @return
	 */
	public static Integer getWorkingYears(String joinWorkDate) {
		if (!StrUtil.isNullOrEmpty(joinWorkDate)) {
			Date now = new Date();
			Long time = 0L;
			time = now.getTime() - DateUtil.patternStrToDate(joinWorkDate).getTime();
			time = time / 1000 / 60 / 60 / 24L;

			return (int) (time / 30);

		}
		return 0;
	}

	/**
	 * 计算预计退休日期：男=出生日期+60年;女=出生日期+50年
	 * 
	 * @param sex
	 * @param birth
	 * @return
	 */
	public static Date getRetiredDate(String sex, String idNum) {

		if (null != sex && null != idNum) {
			// 男
			if ("1001A1100000000006A8".equals(sex)) {
				return getDate(idNum, 60);
			}
			// 女
			if ("1001A1100000000006A9".equals(sex)) {
				return getDate(idNum, 50);
			}
		}

		return null;
	}

	private static Date getDate(String idNum, Integer retiredAge) {
		try {
			String birth = idNum.substring(6, 14);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new SimpleDateFormat("yyyyMMdd").parse(birth));
			calendar.add(Calendar.YEAR, retiredAge);
			return calendar.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 检测填入的参数是否为空
	 */
	public String checkUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getProperty().getSelectedItem().getValue())) {
			return "请选择外包人员属性";
		} else if (StrUtil.isNullOrEmpty(bean.getNationality().getSelectedItem().getValue())) {
			return "请选择民族";
		} else if (StrUtil.isNullOrEmpty(bean.getJoinWorkDate().getValue())) {
			return "请选择参加工作日期";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef3().getValue())) {
			return "请选择进入电信系统日期";
		} else if (StrUtil.isNullOrEmpty(bean.getEnterUnitTime().getValue())) {
			return "请选择进入本单位日期";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef7().getValue())) {
			return "请填写紧急联系人姓名";
		} else if (StrUtil.isNullOrEmpty(bean.getCharacterrpr().getSelectedItem().getValue())) {
			return "请选择户口性质";
		} else if (StrUtil.isNullOrEmpty(bean.getHomePhone().getValue())) {
			return "请输入家庭联系电话";
		} else if (StrUtil.isNullOrEmpty(bean.getHealth().getSelectedItem().getValue())) {
			return "请选择健康状况";
		} else if (StrUtil.isNullOrEmpty(bean.getMarital().getSelectedItem().getValue())) {
			return "请选择婚姻状况";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef8().getValue())) {
			return "请输入紧急联系人手机";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef2().getSelectedItem().getValue())) {
			return "请选择进入电信系统来源";
		} else if (StrUtil.isNullOrEmpty(bean.getEmail().getValue())) {
			return "请输入电子邮件";
		} else if (StrUtil.isNullOrEmpty(bean.getCensusAddr().getValue())) {
			return "请填写户籍地址";
		} else if (StrUtil.isNullOrEmpty(bean.getFileAddress().getValue())) {
			return "请填写档案所在地";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef13().getValue())) {
			return "请填写家庭地址";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef12().getValue())) {
			return "请填写本人户口地址";
		} else if (StrUtil.isNullOrEmpty(bean.getTrialType().getSelectedItem().getValue())) {
			return "请选择试用类型";
		} else if (StrUtil.isNullOrEmpty(bean.getBegindate().getValue())) {
			return "请选择试用开始日期";
		} else if (StrUtil.isNullOrEmpty(bean.getEnddate().getValue())) {
			return "请选择试用结束日期";
		}
		// 判断字符个数，并限制
		else if (bean.getUsedName().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "曾用名字符个数超出限制";
		} else if (bean.getGlbdef7().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "紧急联系人姓名字符个数超出限制";
		} else if (bean.getCensusAddr().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "户籍地址字符个数超出限制";
		} else if (bean.getFileAddress().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "档案所在地字符个数超出限制";
		} else if (bean.getGlbdef12().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "本人户口地址字符个数超出限制";
		} else if (bean.getGlbdef13().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "家庭地址字符个数超出限制";
		} else if (bean.getDieRemark().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "身故说明字符个数超出限制";
		} else if (bean.getMemo().getValue().length() > UecOutStaffConstants.UEC_MAX_COUNT) {
			return "备注字符个数超出限制";
		} else if (bean.getEmail().getValue().length() > UecOutStaffConstants.EMAIL_MAX_COUNT) {
			return "邮件字符个数超出限制";
		} else if (bean.getHomePhone().getValue().length() > UecOutStaffConstants.PHONE_MAX_COUNT) {
			return "家庭电话字符个数超出限制";
		} else if (bean.getGlbdef8().getValue().length() > UecOutStaffConstants.PHONE_MAX_COUNT) {
			return "紧急联系人电话字符个数超出限制";
		}
		return null;
	}

	/**
	 * 将Date类型的日期转换成String类型
	 */
	public void DateFormatter() {
		// 参加工作日期
		uecOutStaffInfo.setJoinWorkDate(DateUtil.dateToStr(bean.getJoinWorkDate().getValue()));
		// 进入电信系统日期
		uecOutStaffInfo.setGlbdef3(DateUtil.dateToStr(bean.getGlbdef3().getValue()));
		// 身故日期
		uecOutStaffInfo.setDieDate(DateUtil.dateToStr(bean.getDieDate().getValue()));
		// 进入本单位日期
		uecOutStaffInfo.setEnterUnitTime(DateUtil.dateToStr(bean.getEnterUnitTime().getValue()));
	}

	/**
	 * 将String类型的日期转换成Date类型
	 */
	public void stringTransToDate() throws ParseException {
		// 参加工作日期
		bean.getJoinWorkDate().setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getJoinWorkDate()));
		// 进入电信系统日期
		bean.getGlbdef3().setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getGlbdef3()));
		// 身故日期
		bean.getDieDate().setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getDieDate()));
		// 进入本单位日期
		bean.getEnterUnitTime().setValue(DateUtil.patternStrToDate(qryUecOutStaffInfo.getEnterUnitTime()));
	}

}
